<!-- @format -->

<template>
	<div class="ma-content-block " style="height:100%">
		
		
		<div class='' v-if="props.list.length != 0">
			<div class=" marbot12" v-if="props.inforow.pick_type == 2 || props.inforow.pick_type == 4">
						配送公司：{{props.inforow.ps_dept.name}}
					</div>
			<div class="flex marbot12">
				<div style="flex:1;width:0;margin-right:16px" v-if="props.inforow.pick_type == 1 || props.inforow.pick_type == 3">
					<a-select  v-model="props.car_no" :filter-option="filterOption" :options="props.carlist" :field-names="fieldNamebangdingsiji"  allow-clear allow-search 
					placeholder="请选择绑定司机" @change="handleselectChange" />
				</div>
				<div style="flex:1;width:0;margin-right:16px" v-if="props.inforow.pick_type == 2 || props.inforow.pick_type == 4">
					<a-select style="" v-model="peisongcarid" :options="peisongcarList" :filter-option="filterOption" :field-names="{value: 'id', label: 'car_and_driver'}"  allow-clear allow-search
					placeholder="请选择绑定司机" @change="handlechangeadderr" />
				</div>
				<a-button type="primary" style="margin-right:16px" @click="handleXiaDan" v-auth="['prediction:deriverOrder:save']" >立即下单</a-button>
				<!-- <a-button @click="getPrientData('',props.inforow.id)">打印</a-button> -->
				<a-button @click="handleTiHuoShow">打印提货单</a-button>
			</div>
			<!-- 集装箱 -->
			<div v-if="props.inforow.transport_type == 1">
				<a-table :columns="columnsJZX" ref="aTableRef" :bordered="{ wrapper: true, cell: true }" :data="props.list" v-model:selectedKeys="selChange" :row-selection="{type: 'checkbox'}" row-key="id" @row-click="rowClick" @selection-change="handleSelChange">
					<template #box="{record}">
						<a-tooltip :content="record?.prediction?.box">
							<div>{{record?.prediction?.box}}</div>
						</a-tooltip>
					</template>
					<template #box_type="{record}">
						<a-tooltip :content="record?.prediction?.box_type">
							<div>{{record?.prediction?.box_type}}</div>
						</a-tooltip>
					</template>
				</a-table>
			</div>
			<!-- 整车 -->
			<div v-else>
				<a-table :columns="columnsZC" ref="aTableRef" :bordered="{ wrapper: true, cell: true }" :data="props.list" v-model:selectedKeys="selChange" :row-selection="{type: 'checkbox'}" row-key="id" @row-click="rowClick" @selection-change="handleSelChange">
					<template #dept_id="{record}">
						<a-tooltip :content="`${record?.prediction?.car_no}`">
							<div>{{record?.prediction?.car_no}}</div>
						</a-tooltip>
					</template>
					
					<template #pick_number="{record}">
						
						<div v-if="((props.inforow.pick_type == 1 || props.inforow.pick_type == 2) && inforow?.transport_type == 2) || 
						((props.inforow.pick_type == 3 || props.inforow.pick_type == 4) && inforow?.transport_type == 2)">
							<a-input
								:default-value="0"
								v-model="record.pick_number"
								placeholder="请填写"
								@change="handlechangeInput($event,record.pick_number,record)"
							>
								<template #append>件</template>
							</a-input>
							<p>
								<a-tag
									style="margin-top: 5px"
									color="blue"
									>剩余件数：{{ (record.pick_number_yu - 0) }}</a-tag
								>
							</p>
						</div>
						<div v-else>{{ record.pick_number }}</div>
					</template>
					<template #pick_weight="{ record }">
						<div v-if="((props.inforow.pick_type == 1 || props.inforow.pick_type == 2) && inforow?.transport_type == 2) || 
						((props.inforow.pick_type == 3 || props.inforow.pick_type == 4) && inforow?.transport_type == 2)">
							<a-input
								:default-value="0"
								
								v-model="record.pick_weight"
								placeholder="请填写"
								@change="handlechangeInput($event,record.pick_weight,record)"
							>
								<template #append>吨</template>
							</a-input>
							<p>
								<a-tag
									style="margin-top: 5px"
									color="blue"
									>剩余吨数：{{ (record.pick_weight_yu - 0).toFixed(3) }}</a-tag
								>
							</p>
						</div>
						<div v-else>{{ record.pick_weight }}</div>
						
					</template>
				</a-table>
			</div>
		</div>
		<div class="flex justify_center align_center" style="height:100%;width:100%" v-if="props.list.length == 0">
			<a-empty />
		</div>
	</div>

	<a-modal :mask-closable="false" 
		v-model:visible="confirmShow"
		:on-before-ok="handleConfirm"
		@cancel="handleCancel"
		:width="1280"
	>
		<template #title> 订单确认 </template>
		<div v-if="confirmShow">
			<div class="text-center m-b-10 font-18">司机：{{ drivers_name }}</div>
			<a-table
				:columns="t_columns"
				:data="news"
				:stripe="false"
				summary-text="合计"
				summary
			>
				<template #pick_number="{ record }">
					{{ record.pick_number || 0 }}件
				</template>
				<template #pick_weight="{ record }">
					{{ record.pick_weight || 0 }}吨
				</template>
				<template #pickType="{ record }">
					<a-tag type="primary">
						{{ record.pickType }}
					</a-tag>
				</template>
				<template #summary-cell="{ column, record, rowIndex }">
						{{
							column.dataIndex == "s_number" ? "合计" : column.dataIndex == "pick_weight"  ? (record[column.dataIndex] - 0).toFixed(3) + '吨' : column.dataIndex == "pick_number"  ? record[column.dataIndex] + '件' : record[column.dataIndex]
						}}
					</template>
			</a-table>
		</div>
	</a-modal>
	<a-modal :mask-closable="false" 
		v-model:visible="numShow"
		:on-before-ok="handleConfirmnumShow"
		@cancel="handleCancelnumShow"
		:width="680"
	>
		<template #title> 温馨提示 </template>
		<div v-if="numShow">
			<div class="text-center m-b-10 font-18">提货件数已超过剩余数量/重量，是否继续下单！</div>
		</div>
	</a-modal>

	<prientTable
		v-model:visibleRecord="prientShow"
		@cancel="cancelPrientPopup"
		:data="p_data"
		:link_id="order_id"
		:drivers="drivers"
		v-if="prientShow"
		:inforow="props.inforow"
	></prientTable>

	<a-modal :mask-closable="false" 
		v-model:visible="tiHuoShow"
		width="auto"
		:title="(props.inforow.pick_type == 2 || props.inforow.pick_type == 4)?'打印配送单':'打印提货单'"
		ok-text="打印"
		:footer="false"
	>
		<paisong :row="props.inforow" :transport_type="props.inforow.transport_type" :deptName="props.inforow.dept.name" :process_time="props.inforow.process_time" :pick_typeid="props.inforow.pick_type" :user="user" v-if="tiHuoShow && (props.inforow.pick_type == 2 || props.inforow.pick_type == 4)"></paisong>
		<ziti :row="props.inforow" :transport_type="props.inforow.transport_type" :deptName="props.inforow.dept.name" :process_time="props.inforow.process_time" :pick_typeid="props.inforow.pick_type" :user="user" v-if="tiHuoShow && (props.inforow.pick_type == 1 || props.inforow.pick_type == 3)"></ziti>
	</a-modal>
</template>
<script setup>
	import { ref, reactive, defineProps, defineEmits,onMounted } from "vue";
	import predictionOrderDetail from "@/api/prediction/predictionOrderDetail";
	import { Message } from "@arco-design/web-vue";
	import { pinyin } from "pinyin-pro"
	import prientTable from "./prient.vue";
	import ziti from "./components/ziti.vue"
	import paisong from "./components/paisong.vue"
	import tool from "@/utils/tool";
	import { request } from "@/utils/request.js";
	import * as common from "@/utils/common";
	import {
		prientShow,
		p_data,
		getPrientData,
		cancelPrientPopup,
	} from "./prient.js";
	import { useUserStore } from "@/store";
	const userStore = useUserStore();
	// 当前登录的用户所有信息，包括 id 用户名 昵称 等信息
	const user = userStore.user;
	const filterOption = (v,option)=>{
		return option.keywords.some(keywords=>keywords.includes(v))
	}

	// 点击行选中
	const aTableRef = ref(null)
	const rowClick = (e) => {
		if(!e.disabled){
			if(selChange.value.includes(e.id)){
				aTableRef.value.select(e.id,false)
			}else{
				aTableRef.value.select(e.id,true)
			}
		}
		
	}
	const tiHuoShow = ref(false)
	const handleTiHuoShow = ()=>{
		tiHuoShow.value = true
	}

	const props = defineProps({
        list:{
            type: Array,
            default:[],
        },
		carlist:{
            type: Array,
            default:[],
        },
        inforow:{
            type: Object,
            default:{},
        },
		ids:{
			type: Array,
            default:[],
		},
		car_no:{
			type: String,
            default:'',
		}
    })
	const contract_id = ref('')
	const is_peisong = ref('')
	const peisongDeptlist = ref([])
	const peisongDeptid = ref('')
	const peisongcarList = ref([])
	const peisongcarid = ref('')
	const peisongaddrrList = ref([])
	const peisongaddrr = ref('')
	const fieldNamebangdingsiji = {value: 'id', label: 'car_and_driver'}
	const selChange = ref([])
	const peisongList =  ref([
		{label:'是',value:'1'},
		{label:'否',value:'0'},
	])
	onMounted(()=>{
		is_peisong.value = ''
		peisongDeptid.value = ''
		peisongcarid.value = ''
		peisongaddrr.value = ''
		peisongDeptlist.value = []
		peisongcarList.value = []
		peisongaddrrList.value = []
		console.log('props.inforow:',props.inforow)
		handlechangeCar(props.inforow.peisong_dept_id)
	})
	// const handlepeisongDeptlist = () =>{
	// 	request({
	// 		url: 'system/dept/remote',
	// 		method: 'post',
	// 		data: {
	// 		openPage: false,
	// 		remoteOption: {
	// 			filter: {
	// 			type: ['=', 3]
	// 			},
	// 			select: ["id", "name"],
	// 			sort: { id: "desc" }
	// 		}
	// 		}
	// 	}).then(res => {
	// 		peisongDeptlist.value = res.data
			
	// 	})
	// }
	const handlechangeCar = (e)=>{   // 选择公司后获取司机
		request({
			url: '/prediction/driver/getCarNoList?dept_id=' + e,
			method: 'get',
			
		}).then(res=>{
			res.data.map((v,i)=>{
					v.keywords = [
					v.car_and_driver,
					pinyin(v.car_and_driver,{toneType:'none',pattern:'first'}).split(' ').join(''),
					pinyin(v.car_and_driver,{toneType:'none',pattern:'first'}).split(' ').join('').toUpperCase()
					]
			})
			peisongcarList.value = res.data
			peisongcarid.value = ''
			console.log('list:',props.list)
			
		})
	}
	const handlechangeadderr = () =>{   // 获取合同配送地址
		props.list.map((v,i)=>{
			contract_id.value = v.prediction.contract_id
		})
		request({
			url: '/system/userContractAddress/index?contract_id=' + contract_id.value,
			method: 'get',
			
		}).then(res=>{
			peisongaddrr.value = ''
			peisongaddrrList.value = res.data.items
		})
	}
	
	const num = ref(-1);
	const numShow = ref(false);
	const acc = ref([]);
	const ccc = ref(true);
	const addshow = ref(true)
	const crudRefYBDZC = ref();
	const crudRefYBDJZX = ref();
	const crudRefCKPT = ref();
	const crudRefCKJZ = ref();
	const crudRefCKJZX = ref();
	const order_id = ref();
	const tableArr = ref([]);
	const tableData = ref();
	const drivers = ref([]);
	let drivers_id = ref(null);
	const drivers_name = ref("");
	let old = [];
	let news = [];
	const confirmShow = ref(false);
	const d_method = ref(["普通提货", "精准提货", "集装箱"]);

	function d_change(id) {
		drivers_name.value =
			drivers.value.find((item) => item.value == id)?.label || "";
	}

	// 声明emits
	const $emit = defineEmits(["change","gengxincar","shuaxin"]);

	// 重构 -- 集装箱
	const columnsJZX = reactive([
		{
			title: "箱号",
			dataIndex: "address",
			align: "center",
			ellipsis: true,
        	tooltip: true,
			slotName:'box'
		},
		{
			title: "箱型箱类",
			dataIndex: "area",
			align: "center",
			ellipsis: true,
        	tooltip: true,
			slotName:'box_type'
		},
		{
			title: "件数",
			dataIndex: "pick_number",
			align: "center",
			width:100,
			ellipsis: true,
        	tooltip: true,
			slotName:'pick_number'
		},
		{
			title: "重量",
			dataIndex: "pick_weight",
			align: "center",
			width:100,
			ellipsis: true,
        	tooltip: true,
			slotName:'pick_weight'
		},
	])
	// 重构 -- 整车
	const columnsZC = reactive([
		
		
		{
			title: "发站/车号",
			dataIndex: "dept_id",
			align: "center",
			ellipsis: true,
			width:120,
        	tooltip: true,
			slotName:'dept_id'
		},
		{
			title: "件数",
			dataIndex: "pick_number",
			align: "center",
			width:140,
			ellipsis: true,
        	tooltip: true,
			slotName:'pick_number'
		},
		{
			title: "重量",
			dataIndex: "pick_weight",
			align: "center",
			width:140,
			ellipsis: true,
        	tooltip: true,
			slotName:'pick_weight'
		},
		
	])
	const handleselectChange = (e)=>{
		console.log(e)
		$emit('gengxincar',e)
	}
	// 重构-- 下单
	const handleXiaDan = async ()=>{
		if(props.inforow.pick_type == 2 || props.inforow.pick_type == 4){
			if (!peisongcarid.value) {
				return Message.error("请选择配送司机");
			}
		}else{
			if (!props.car_no) {
				return Message.error("请选择司机");
			}
		}
		
		let news = []
		props.list.map((v,i)=>{
			selChange.value.map((vv,ii)=>{
				if(v.id == vv){
					news.push(v)
				}
			})
		})
		if (news.length < 1) {
			return Message.error("请选择");
		}
		let objectItem = {}
		objectItem.type = 1
		if(props.inforow.pick_type == 2 || props.inforow.pick_type == 4){
			objectItem.ps_car_id = peisongcarid.value
			objectItem.detail = news
		}else{
			objectItem.order_car_id = props.car_no
			objectItem.detail = news
		}


		let res = await predictionOrderDetail.addOrders(objectItem);
		if (res.code == 200) {
			selChange.value = []
			Message.success('下单成功！')
			$emit("shuaxin");
		} else {
			Message.error("下单失败");
			$emit("shuaxin");
		}
	}

	// 选中
	const handleSelChange = (item)=>{
		console.log('选中的数据：',item)
		selChange.value = item
	}


	

	

	const numberOperation = (newValue, id, numberName) => {
		predictionOrderDetail
			.numberOperation({ id, numberName, numberValue: newValue })
			.then((res) => {
				res.success && Message.success(res.message);
			})
			.catch((e) => {
				console.log(e);
			});
	};

	const switchStatus = (statusValue, id, statusName) => {
		predictionOrderDetail
			.changeStatus({ id, statusName, statusValue })
			.then((res) => {
				res.success && Message.success(res.message);
			})
			.catch((e) => {
				console.log(e);
			});
	};

	const options = reactive({
		id: "flyos_prediction_order_detail",
		rowSelection: {
			showCheckedAll: true,
		},
		pk: "id",
		operationColumn: false,
		isDbClickEdit: false,
		// pageSize:100,
		// pageSizeOption:[30],
		operationWidth: 190,
		bordered: { cell: true },
		// expandSearch:false,
		formOption: {
			viewType: "modal",
			width: 600,
		},
		api: predictionOrderDetail.getList,
		recycleApi: predictionOrderDetail.getRecycleList,
		add: {
			show: false,
			api: predictionOrderDetail.save,
			auth: ["prediction:orderDetail:save"],
		},
		edit: {
			show: false,
			api: predictionOrderDetail.update,
			auth: ["prediction:orderDetail:update"],
		},
		delete: {
			show: false,
			api: predictionOrderDetail.deletes,
			auth: ["prediction:orderDetail:delete"],
			realApi: predictionOrderDetail.realDeletes,
			realAuth: ["prediction:orderDetail:realDeletes"],
		},
		recovery: {
			show: false,
			api: predictionOrderDetail.recoverys,
			auth: ["prediction:orderDetail:recovery"],
		},
		import: {
			show: false,
			url: "prediction/orderDetail/import",
			templateUrl: "prediction/orderDetail/downloadTemplate",
			auth: ["prediction:orderDetail:import"],
		},
		export: {
			show: false,
			url: "prediction/orderDetail/export",
			auth: ["prediction:orderDetail:export"],
		},
		beforeRequest: (params) => {
			params.order_id = order_id.value;
			params.order = "created_at";
			params.orderType = "desc";
		},
		afterRequest: (params) => {
			params.map((v, i) => {
				if (v.pick_number_yu == 0) {
					v.disabled = true;
					v.pick_number = v.pick_number_yu;
					v.pick_weight = v.pick_weight_yu;
				} else {
					v.disabled = false;
					v.pick_number = v.pick_number_yu;
					v.pick_weight = v.pick_weight_yu;
				}
			});
		},
	});
	

	// 确认订单表格
	let t_columns = [];

	// 确认弹窗关闭
	const handleCancel = () => {
		confirmShow.value = false;
	};
	const handleCancelnumShow = () => {
		numShow.value = false;
	};
	// 确认弹窗确认
	const handleConfirmnumShow = async () => {
		let res = await predictionOrderDetail.addOrders({
			order_car_id: drivers_id.value,
			detail: news,
		});
		if (res.code == 200) {
			numShow.value = false
			$emit("change", 1);
			return true
		} else {
			numShow.value = false
			$emit("change", 2);
			return false
		}
	};
	// 确认弹窗确认
	const handleConfirm = async () => {
		num.value = news.findIndex(item=>{
			return ((item.pick_number - 0) > (item.pick_number_yu - 0))  || ((item.pick_weight - 0) > (item.pick_weight_yu - 0))
		})
		if(num.value > -1){
			return numShow.value = true
		}
		let res = await predictionOrderDetail.addOrders({
			order_car_id: drivers_id.value,
			detail: news,
		});
		if (res.code == 200) {
			$emit("change", 1);
			return true
		} else {
			$emit("change", 2);
			return false
		}
	};

	defineExpose({ open });
</script>
<script>
	export default { name: "prediction:orderDetail" };
</script>

<style lang="less" scoped>
	.m-b-10 {
		margin-bottom: 10px;
	}

	.font-18 {
		font-size: 18px;
	}
	.marbot12{
		margin-bottom:12px;
	}
</style>
